import config from './config.js';
import tools from "./tools.js";

/**
 * 生成随机密钥
 */
function getRandomKey() {
	const user = getLoginUser();
	const seconds = Date.parse(new Date())/1000;
	
	const res = user.id+"_"+parseInt(Math.random()*seconds);
	return res;
}

function getLoginUser() {
	const user = uni.getStorageSync(config.CUR_CUSTOM);
	return user;
}

//存入缓存
function setLoginUser(obj) {
	uni.setStorageSync(config.CUR_CUSTOM, obj);
}

function setCurShop(shop) {
	uni.setStorageSync("CURRENT_SHOP", shop);
}

function getCurShop() {
	return uni.getStorageSync("CURRENT_SHOP");
}

function setOpenid(openid) {
	uni.setStorageSync("CUR_OPENID", openid);
}

function getOpenid() {
	return uni.getStorageSync("CUR_OPENID");
}

function setCustomer(obj) {
	uni.setStorageSync("CURRENT_CUSTOMER", obj);
}

function getCustomer() {
	return uni.getStorageSync("CURRENT_CUSTOMER");
}

/**
 * 缓存数据,带到期时间
 * @param {Object} key
 * @param {Object} value
 * @param {Object} seconds
 */
function setStorageTime(key, value, seconds) {
	var timestamp = parseInt(Date.parse(new Date())/1000); //当前时间的秒数
	const dataType = Object.prototype.toString.call(value);
	let isObj = false;
	if(dataType === '[object Object]') { //如果value是一个对象
		isObj = true;
	}
	let newData = {
		isObj: isObj,
		timeout: timestamp+seconds,
		value: value
	};
	uni.setStorageSync(key, JSON.stringify(newData));
}

/**
 * 获取缓存数据,带到期时间
 * @param {Object} key
 */
function getStorageTime(key) {
	var timestamp = parseInt(Date.parse(new Date())/1000); //当前时间的秒数
	const dataStr = uni.getStorageSync(key);
	if(dataStr) {
		const data = JSON.parse(dataStr);
		//console.log(data);
		if(timestamp>data.timeout) { //表示过期
			uni.removeStorageSync(key);
			return null;
		} else {
			/* if(data.isObj) {
				return JSON.parse(data.value);
			} else {
				return data.value;
			} */
			return data.value;
		}
	} else {
		return null;
	}
}

/**
 * 将参数对象转换成参数形式
 * @param {Object} obj
 */
function obj2Query(obj) {
	let query = "?";
	for(let key in obj) {
		query += (key+"="+obj[key]+"&");
	}
	// console.log(query)
	return query;
}

/** 把App.vue中的参数存入session中 */
function setAppQuery(query) {
	// console.log("----App query---->", query)
	uni.setStorageSync("app-query", JSON.stringify(query));
}

/**
 * 获取当前页面
 */
function getCurrentPage() {
	const pages = getCurrentPages();
	// console.log(pages)
	const curPage = pages[pages.length-1];
	
	const route = curPage.route;
	let options = curPage.options;
	// console.log("==============", options)
	if(!options) {
		options = JSON.parse(uni.getStorageSync("app-query"));
	}
	// console.log("------------", options)
	const url = "/"+route + obj2Query(options);
	
	// console.log(url);
	return url;
}

function gotoBack() {
	// console.log("====goback===")
	const pages = getCurrentPages();
	// console.log(pages);
	if(pages.length<=1) {
		uni.switchTab({
			url:"/pages/index/index"
		})
	} else {
		uni.navigateBack();
	}
}

function gotoUserPage() {
	const curPage = getCurrentPage();
	const pwd = escape(curPage);
	// console.log(curPage, pwd);
	uni.showToast({
		title: '为获取优质服务,请先授权', 
		icon:"none",
		success() {
			//跳转到登陆页面
			uni.redirectTo({
				url: '/pages/login/wx?url='+pwd
			});
		}
	});
	//console.log(tools.unPassword(pwd));
}

function gotoTargetPage(urlPwd) {
	let url = unescape(urlPwd);
	console.log(url);
	try { //URL可能是民航也可能是内页,所以执行两个不同的方法,但只能成功一个
		uni.redirectTo({
			url: url
		});
		//if(url.indexOf("?")>=0) {url = url.split("?")[0];}
		uni.reLaunch({
			url: url
		});
		//console.log("-----------", url)
	} catch(e) {
	}
}

function reloadPage(url) {
	/* uni.redirectTo({
		url:url
	}) */
	uni.reLaunch({
		url: url
	})
}

function reloadCur() {
	const url = getCurrentPage();
	reloadPage(url);
}

function rebuildMoney(money) {
	if(isNaN(money)) {return 0;}
	return Number(parseFloat(money).toFixed(2));
}

function goBack() {
	uni.navigateBack();
}

function checkFromSource() {
	let from = '';
	const info = uni.getSystemInfoSync();
	const platform = info.uniPlatform;
	if(platform==='mp-weixin') {
		from = 'wx';
	} else if(platform ==='mp-toutiao') {
		from = 'tt';
	}
	return from;
}

function showNormalToast(msg) {
	uni.showToast({
		title: msg, icon: "none"
	})
}

function setCurrentType(type) {
	uni.setStorageSync("current-type", type);
}
function getCurrentType() {
	return uni.getStorageSync("current-type");
}

function buildValidEndDay(validDays) {
	let newDate = new Date();
	// 获取当前日期的天数并加一
	// let day = newDate.getDate();
	newDate.setDate(newDate.getDate() + validDays);
	
	let year = newDate.getFullYear();
	let month = newDate.getMonth() + 1;
	let day = newDate.getDate();
	
	month = month > 9 ? month : '0' + month;
	day = day > 9 ? day : '0' + day;
	return `${year}-${month}-${day}`;
}

function buildSex(sex) {
	if(sex==='1') {return "男";}
	else if(sex==='2') {return "女";}
	else {return "-";}
}

function callPhone(phone) {
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

export default {
	getLoginUser: getLoginUser,
	setLoginUser: setLoginUser,
	setStorageTime: setStorageTime,
	getStorageTime: getStorageTime,
	obj2Query: obj2Query,
	getCurrentPage: getCurrentPage,
	gotoUserPage: gotoUserPage,
	gotoTargetPage: gotoTargetPage,
	getRandomKey: getRandomKey,
	reloadPage: reloadPage,
	reloadCur: reloadCur,
	rebuildMoney: rebuildMoney,
	goBack: goBack,
	setAppQuery: setAppQuery,
	gotoBack: gotoBack,
	setCurShop: setCurShop,
	getCurShop: getCurShop,
	setOpenid: setOpenid,
	getOpenid: getOpenid,
	getCustomer: getCustomer,
	setCustomer: setCustomer,
	checkFromSource: checkFromSource,
	showNormalToast: showNormalToast,
	setCurrentType: setCurrentType,
	getCurrentType: getCurrentType,
	buildValidEndDay: buildValidEndDay,
	buildSex: buildSex,
	callPhone: callPhone
}